<template>
  <!--列表-->
  <section>
    <el-form :inline="true" :model="AdminQuery" class="toolbar"
             style="text-align: left;margin-top: 20px">
      <el-form-item label="关键字">
        <el-input v-model="AdminQuery.keyword" placeholder="请输入昵称进行查询"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="success" @click="addDepartment">新增</el-button>
        <el-button type="success" @click="exportExcel">按需导出</el-button>
      </el-form-item>

    </el-form>
    <el-table :data="listDatas" highlight-current-row row-key="id" v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;" element-loading-text="拼命加载中">
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="200">
      </el-table-column>
      <el-table-column prop="isLogin" label="是否已登录" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.isLogin == 0" style="color: red">否</span>
          <span v-if="scope.row.isLogin == 1" style="color: green">是</span>
        </template>
      </el-table-column>
      <el-table-column prop="loginInfoId" label="登录Id" width="120">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="120">
      </el-table-column>
      <el-table-column prop="headImage" label="头像地址" width="200">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-popconfirm
          confirmButtonText='忍心抛弃'
          cancelButtonText='再给一次机会'
          icon="el-icon-info"
          iconColor="red"
          title="你确定要离我而去？"
          @confirm="batchRemove"
      >
        <el-button type="danger" slot="reference" :disabled="this.sels.length===0">批量删除</el-button>
      </el-popconfirm>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="sizes"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="pageSize" :total="totalCount" style="float:right;">
      </el-pagination>
    </el-col>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="AdminForm" :rules="AdminForm" ref="AdminForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="AdminForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="AdminForm.password" :disabled="isEditMode" ></el-input>
        </el-form-item>
        <el-form-item label="是否已登录" :label-width="formLabelWidth">
          <el-select max="120" v-model="AdminForm.isLogin"  :disabled="true">
            <el-option :value="0" label="否"></el-option>
            <el-option :value="1" label="是"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录Id" :label-width="formLabelWidth">
          <el-input type="text" v-model="AdminForm.loginInfoId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input type="email" v-model="AdminForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像地址" :label-width="formLabelWidth">
        <el-input type="text" v-model="AdminForm.headImage"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogProgress" style="text-align: center">
      <el-progress type="circle" :percentage="num" :status="success"></el-progress>
    </el-dialog>

  </section>

</template>

<script>

export default {
  data() {
    return {
      success: "",
      isEditMode:true,
      num: null,
      addLoading: false,
      listDatas: [],
      listLoading: true,
      sels: [],
      sizes: [5, 10, 20, 50],
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      AdminQuery: {
        keyword: '',
      },
      formLabelWidth: '120px',
      title: "新增",
      AdminForm: {
        id: null,
        username: '',
        password:'',
        isLogin: '',
        loginInfoId: '',
        email: '',
        headImage: '',
      },
      dialogProgress: false,
      dialogFormVisible: false,
      dialogExportExcel: false,
    }
  },
  methods: {
    //批量删除
    batchRemove() {
      //把对象数组转成 id数组
      let deptIds = this.sels.map(function (obj, index, array) {
        return obj.id;
      })
      if (deptIds.concat(1)){
        this.$message.error("不允许删除!")
        return
      }
      this.$http.delete("/admin/user/deleteList", {data: deptIds}).then(res => {
        let {msg, success} = res.data
        if (success) {
          //操作成功   给一条提示
          this.$message.success("删除成功");
        } else {
          //操作失败  给一条失败的提示
          this.$message.error("操作失败")
        }
        this.loadListData();
      })
    },
    exportExcel() {
      console.log(this.sels)
      if (this.sels.length != 0) {
        this.title = "正在下载..."
        this.dialogProgress = true;
        this.num = 0;
        this.$http.put("/admin/admin/exportMore", this.sels, {responseType: 'blob'}).then(res => {
          this.num = 30;
          let resBlob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          let a = document.createElement("a");
          let url = URL.createObjectURL(resBlob);
          this.num = 50;
          //将url赋值给a标签的href属性
          a.href = url;
          //下载的文件的文件名
          a.download = "管理员数据表.xlsx";
          this.num = 70;
          //触发click事件执行下载
          a.click();
          //要记得回收URL
          URL.revokeObjectURL(url);
          this.num = 100;
          this.success = "success";
          this.title = "下载完成!"
        })
      } else {
        this.$message.error("没有选择数据")
      }

    },
    loadListData() {
      //2、组装分页数据
      let param = {
        keyword: this.AdminQuery.keyword,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }
      this.$http.post("/admin/admin", param).then(res => {
        let {data, success, msg} = res.data;
        if (success) {
          this.listDatas = data.rows;
          this.totalCount = data.total;
          //关闭加载效果
          this.listLoading = false;
        } else {
          this.$message.error(msg)
        }
      })
    },
    selsChange: function (sels) {
      this.sels = sels;
      console.log(this.sels)
    },
    //删除
    handleDel: function (index, row) {
      if (row.id == 1){
        this.$message({
          type: 'error',
          message: '不允许删除!'
        });
        return
      }
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/admin/admin/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
          if (this.totalCount / this.pageSize)
            this.loadListData();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      //1、获取当前行的数据
      //2、数据回显
      //3、打开弹出框
      this.title = '修改';
      this.AdminForm = row;
      this.dialogFormVisible = true;
      this.isEditMode = true;
    },
    //显示新增界面
    addDepartment: function () {
      //1、清空表单数据
      this.AdminForm = {
        id: null,
        username: '',
        password:'',
        isLogin: '',
        loginInfoId: '',
        email: '',
        headImage: '',
      }
      this.isEditMode = false;
      this.title = '新增';
      //2、打开弹出框
      this.dialogFormVisible = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.loadListData();
    },
    handleCurrentChange(val) {
      //val 就是当前页的页码
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadListData();
    },
    onSearch() {
      this.listLoading = true;
      this.loadListData();
    },
    onSubmit() {
      this.$refs.AdminForm.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.$http.put('/admin/admin/saveOrUpdate', this.AdminForm).then(res => {
              this.addLoading = false;
              if (res.data.success) {
                this.$message.success("添加操作成功！");
              } else {
                this.$message.error("添加操作失败！");
              }
              this.dialogFormVisible = false;
              this.loadListData();
            });
          }).catch(() => {
            this.addLoading = false;
            this.$message.info("取消操作");
          })
        }
      });
    },
  },
  mounted() {
    //加载完毕以后调用获取列表数据的方法
    this.loadListData();
  }
}
</script>

<style scoped>

</style>